package org.jfk.tbox.plugin;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jfk.tbox.net.TcpServerHandler;

import com.jfinal.plugin.IPlugin;

public class TboxTcpServerPlugin implements IPlugin {
	private static Logger logger = Logger.getLogger(TboxTcpServerPlugin.class);	

	public static final int TERMINAL_TIMEOUT = 1000*60*3;
	public static final int HTTPSESSION_TIMEOUT = 1000*60*30;
	public static final int CHECK_INTERVAL = 1000*1;
	
	public static int tcpConnCount = 0;
	public static String tcpConnCountLock = "";//防止计数不准

	public static int tcpMsgRecvCount = 0;
	public static int tcpMsgQCount = 0;
	public static String tcpMsgRecvCountLock = "";//防止计数不准
	
	public static int tcpMsgRevErrCount = 0;
	
	public static int tcpExceptionCaught = 0;
	
	public static final Map onlineTerminals = new HashMap();
	
	public boolean start() {
		logger.debug("TboxTcpServerPlugin start !!!");
		//1、创建channelfactory
//		ChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors
//				.newCachedThreadPool(), Executors.newCachedThreadPool(),16);
		ChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors
				.newCachedThreadPool(), Executors.newCachedThreadPool());//默认线程数为cpu core的2倍

		//2、根据channelfactory创建Server
		ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
		
		//3、通过Server取pipeline
		ChannelPipeline pipeline = bootstrap.getPipeline();
		
		//4、创建Handler
		TcpServerHandler handler = new TcpServerHandler();
		
		//5、为pipeline添加handler
		pipeline.addLast("0", handler);
		
		//6、设置Server的参数
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);

		//7、绑定IP和端口，启动服务
		//Channel channel = bootstrap.bind(new InetSocketAddress(59090));		
		Channel channel = bootstrap.bind(new InetSocketAddress(9009));
		
		
		logger.debug("CheckOnline start !!!");
		new Thread(new CheckOnline()).start();
		
		return true;
	}

	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

	
	public class CheckOnline implements Runnable {

		public void run() {
			while (true) {
				try {
					Thread.sleep(CHECK_INTERVAL);

					/**
					 * 剔除超时不在线的车辆
					 */
					Iterator itr = onlineTerminals.keySet()
							.iterator();
					while (itr.hasNext()) {
						Object mdn = itr.next();
					}


				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

	}	
}
